import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  IconButton,
  Tooltip,
  Chip,
  Snackbar,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  InputAdornment,
} from '@mui/material';
import {
  ContentCopy,
  Share,
  Info,
  Link,
  AccessTime,
  People,
} from '@mui/icons-material';
import { Participant, WebRTCConnectionState } from '@/types';
import { copyToClipboard, generateRoomUrl } from '@/utils/helpers';
import { SUCCESS_MESSAGES } from '@/utils/constants';

interface RoomInfoProps {
  roomId: string;
  participants: Participant[];
  connectionState: WebRTCConnectionState;
}

const RoomInfo: React.FC<RoomInfoProps> = ({
  roomId,
  participants,
  connectionState,
}) => {
  const [showCopySuccess, setShowCopySuccess] = useState(false);
  const [showRoomInfo, setShowRoomInfo] = useState(false);
  const [callDuration, setCallDuration] = useState(0);
  const [callStartTime] = useState(Date.now());

  const roomUrl = generateRoomUrl(roomId);

  // 通话时长计时器
  useEffect(() => {
    const timer = setInterval(() => {
      setCallDuration(Math.floor((Date.now() - callStartTime) / 1000));
    }, 1000);

    return () => clearInterval(timer);
  }, [callStartTime]);

  const handleCopyRoomUrl = async () => {
    const success = await copyToClipboard(roomUrl);
    if (success) {
      setShowCopySuccess(true);
    }
  };

  const handleShareRoom = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: 'FaceTime 视频通话邀请',
          text: `加入我的视频通话房间: ${roomId}`,
          url: roomUrl,
        });
      } catch (error) {
        console.log('分享取消或失败:', error);
        // 降级到复制链接
        handleCopyRoomUrl();
      }
    } else {
      // 降级到复制链接
      handleCopyRoomUrl();
    }
  };

  const formatDuration = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const getConnectionStatusColor = () => {
    switch (connectionState) {
      case 'connected':
        return 'success';
      case 'connecting':
        return 'warning';
      case 'disconnected':
      case 'failed':
        return 'error';
      default:
        return 'default';
    }
  };

  const getConnectionStatusText = () => {
    switch (connectionState) {
      case 'connected':
        return '通话中';
      case 'connecting':
        return '连接中';
      case 'disconnected':
        return '已断开';
      case 'failed':
        return '连接失败';
      default:
        return '未知状态';
    }
  };

  return (
    <>
      <Paper
        elevation={1}
        sx={{
          p: 2,
          mb: 2,
          borderRadius: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          backgroundColor: 'background.paper',
        }}
      >
        {/* 左侧信息 */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Box>
            <Typography variant="h6" sx={{ fontWeight: 600, mb: 0.5 }}>
              房间: {roomId}
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Chip
                icon={<AccessTime />}
                label={formatDuration(callDuration)}
                size="small"
                variant="outlined"
                color="primary"
              />
              <Chip
                icon={<People />}
                label={`${participants.length} 人`}
                size="small"
                variant="outlined"
                color="secondary"
              />
              <Chip
                label={getConnectionStatusText()}
                size="small"
                color={getConnectionStatusColor()}
                variant="filled"
              />
            </Box>
          </Box>
        </Box>

        {/* 右侧操作按钮 */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Tooltip title="复制房间链接">
            <IconButton
              onClick={handleCopyRoomUrl}
              sx={{
                color: 'primary.main',
                '&:hover': {
                  backgroundColor: 'primary.light',
                  color: 'primary.dark',
                },
              }}
            >
              <ContentCopy />
            </IconButton>
          </Tooltip>

          {navigator.share && (
            <Tooltip title="分享房间">
              <IconButton
                onClick={handleShareRoom}
                sx={{
                  color: 'primary.main',
                  '&:hover': {
                    backgroundColor: 'primary.light',
                    color: 'primary.dark',
                  },
                }}
              >
                <Share />
              </IconButton>
            </Tooltip>
          )}

          <Tooltip title="房间信息">
            <IconButton
              onClick={() => setShowRoomInfo(true)}
              sx={{
                color: 'text.secondary',
                '&:hover': {
                  backgroundColor: 'action.hover',
                },
              }}
            >
              <Info />
            </IconButton>
          </Tooltip>
        </Box>
      </Paper>

      {/* 房间信息对话框 */}
      <Dialog
        open={showRoomInfo}
        onClose={() => setShowRoomInfo(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Info color="primary" />
            房间信息
          </Box>
        </DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, pt: 1 }}>
            {/* 房间ID */}
            <TextField
              label="房间ID"
              value={roomId}
              variant="outlined"
              InputProps={{
                readOnly: true,
                endAdornment: (
                  <InputAdornment position="end">
                    <Tooltip title="复制房间ID">
                      <IconButton
                        onClick={() => copyToClipboard(roomId)}
                        edge="end"
                      >
                        <ContentCopy />
                      </IconButton>
                    </Tooltip>
                  </InputAdornment>
                ),
              }}
              fullWidth
            />

            {/* 房间链接 */}
            <TextField
              label="房间链接"
              value={roomUrl}
              variant="outlined"
              InputProps={{
                readOnly: true,
                startAdornment: (
                  <InputAdornment position="start">
                    <Link />
                  </InputAdornment>
                ),
                endAdornment: (
                  <InputAdornment position="end">
                    <Tooltip title="复制链接">
                      <IconButton
                        onClick={handleCopyRoomUrl}
                        edge="end"
                      >
                        <ContentCopy />
                      </IconButton>
                    </Tooltip>
                  </InputAdornment>
                ),
              }}
              fullWidth
              multiline
              rows={2}
            />

            {/* 统计信息 */}
            <Box>
              <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
                通话统计
              </Typography>
              <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                <Chip
                  icon={<AccessTime />}
                  label={`通话时长: ${formatDuration(callDuration)}`}
                  variant="outlined"
                  color="primary"
                />
                <Chip
                  icon={<People />}
                  label={`参与人数: ${participants.length}`}
                  variant="outlined"
                  color="secondary"
                />
                <Chip
                  label={`连接状态: ${getConnectionStatusText()}`}
                  variant="outlined"
                  color={getConnectionStatusColor()}
                />
              </Box>
            </Box>

            {/* 使用提示 */}
            <Box>
              <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
                使用提示
              </Typography>
              <Typography variant="body2" color="text.secondary">
                • 复制房间链接分享给朋友即可邀请加入
                <br />
                • 支持最多2人同时通话
                <br />
                • 房间在最后一人离开后5分钟自动销毁
                <br />
                • 建议使用Chrome或Edge浏览器以获得最佳体验
              </Typography>
            </Box>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowRoomInfo(false)} color="primary">
            关闭
          </Button>
        </DialogActions>
      </Dialog>

      {/* 复制成功提示 */}
      <Snackbar
        open={showCopySuccess}
        autoHideDuration={2000}
        onClose={() => setShowCopySuccess(false)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert onClose={() => setShowCopySuccess(false)} severity="success">
          {SUCCESS_MESSAGES.LINK_COPIED}
        </Alert>
      </Snackbar>
    </>
  );
};

export default RoomInfo;